<?php

namespace app\admin\app\controller;

use app\admin\app\model\ActionLogBeizhu;
use Illuminate\Support\Facades\Cache;
use support\Request;
use support\Response;
use app\admin\app\model\ActionLog;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;
use support\utils\Ip;

/**
 * 操作日志 
 */
class ActionLogController extends Crud
{
    
    /**
     * @var ActionLog
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new ActionLog;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('app/action-log/index');
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        // 修改排序方式
        $order = "desc";
        $field = 'id';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    // 查询后置操作
    public function afterQuery($items)
    {
        foreach ($items as $k=>$v){
            $items[$k]['action_name'] = ActionLogBeizhu::where(['url'=>$v['url']])->value('action_name');
            $items[$k]['ip'] .= "(".ipFind($v['ip']).")";
        }

        return $items; // TODO: Change the autogenerated stub
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('app/action-log/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {

        if ($request->method() === 'POST') {
            $name = $request->input('action_name');
            $id = $request->input('id');
            $url = ActionLog::where(['id'=>$id])->value('url');
            $beizhu = ActionLogBeizhu::where(['url'=>$url])->first(['id','action_name']);
            if($beizhu && $beizhu['id']){
                if($beizhu['action_name']!=$name){
                    // 更新
                    $beizhu['action_name'] = $name;
                    $beizhu->save();
                }
            }else{
                // 新增
                $id = ActionLogBeizhu::insertGetId(['url'=>$url,'action_name'=>$name]);
            }
            return $this->json(0, 'ok', ['id' => $id]);
        }
        return view('app/action-log/update');
    }

}
